import { Feature } from 'ol';
import { fromLonLat } from 'ol/proj';
import { Heatmap } from 'ol/layer';
import { Point } from 'ol/geom';
import VectorSource from 'ol/source/Vector';


export class HeatMapLayer {
	source: VectorSource<Feature<Point>>;
	layer: Heatmap<Feature<Point>>;
	max_weight = 0;

	constructor() {
		const features = [] as Feature<Point>[];

		this.source = new VectorSource({ features });

		this.layer = new Heatmap({
			source: this.source,
			blur: 1,
			radius: 2,
			gradient: ['#DAFDBA', '#9AEBA3', '#45C4B0', '#13678A', '#012030'],
			weight: (feature) => {
				return feature.get('w') / this.max_weight;
			}
		});
	}


	update(lat: number[][], lon: number[][], weight: number[][]) {
		this.source.clear();
		this.max_weight = 0;

		weight.forEach((w_line, i) => {
			w_line.forEach((w, j) => {
				if (w < 0) return;

				if (w > this.max_weight) {
					this.max_weight = w;
				}

				this.source.addFeature(new Feature({
					geometry: new Point(fromLonLat([lon[i][j], lat[i][j]])),
					w: w
				}));
			});
		});
	}
}